package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyJiYiHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeJiYiHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 吉意花
 *
 * 全流程 - 文档：https://pcn0w2zw9cgu.feishu.cn/docx/FgtDdw2hToH7eVx1atMcvXqwnj2?from=from_copylink
 *         密码：2J887#17
 *
 * @author gwc
 * @create 2025-07-30 下午2:18
 */
@ApiPlan(productId = "382", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatJiYiHuaPhoneMask implements ApiPlatformPhoneMaskConvertHandler {

    public static final String KEY = "HIEPnWd1ry1etMeR";
    public static final String CHANNEL_CODE = "ONA65N81";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        // 创建撞库实体类
        ApiPlatDataExchangeJiYiHua jiYiHuaData = new ApiPlatDataExchangeJiYiHua();

        // 手机号掩码，支持 7/8/9 位，例如：15928777***
        jiYiHuaData.setPhoneMask(apiDataExchangeParameter.getPhoneMask());
        // 用户姓名，无则默认 "默认姓名"
        jiYiHuaData.setUserName("默认姓名");
        // 性别（0：女，1：男），默认：1
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", 0)
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .end(1);
        jiYiHuaData.setSex(sex);
        // 年龄，范围：20-55 岁
        jiYiHuaData.setAge(Integer.valueOf(apiDataExchangeParameter.getAge()));
        // 用户 IP，无则默认 127.0.0.1
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            jiYiHuaData.setIp(apiDataExchangeParameter.getIp());
        } else {
            jiYiHuaData.setIp("127.0.0.1");
        }
        // 贷款金额（单位：元），默认：50000 元
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(50000);
        jiYiHuaData.setLoanMoney(money);
        // 城市编码
        jiYiHuaData.setCityCode(apiDataExchangeParameter.getAreaCode());
        // 城市名称（带“市”）
        jiYiHuaData.setCityName(apiDataExchangeParameter.getCity());
        // 职业信息：1-上班族，2-公务员/事业单位，3-私营业主，4-个体户，5-其他；默认：1
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 5)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 2)
                .when(apiDataExchangeParameter.getCareer(), "5", 4)
                .end(1);
        jiYiHuaData.setJob(job);
        // 最低月收入：1-4000以下，2-4000~8000，3-8000~1.5万，4-1.5万~2万，5-2万~3万，6-3万以上；默认：2
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", 1)
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", 2)
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", 3)
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", 5)
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", 6)
                .end(2);
        jiYiHuaData.setMonthlyIncome(monthlySalary);
        // 营业执照情况：1-未办理，2-已办理（注册满1年），3-已办理（注册满3年），4-已办理（注册满5年以上）；默认：1
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiDataExchangeParameter.getBizLicenseYear(),"1", 1)
                .when(apiDataExchangeParameter.getBizLicenseYear(),"2", 2)
                .when(apiDataExchangeParameter.getBizLicenseYear(),"3", 3)
                .when(apiDataExchangeParameter.getBizLicenseYear(),"4", 4)
                .end(1);
        jiYiHuaData.setBusLicense(bizLicenseYear);
        // 社保情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 3)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(1);
        jiYiHuaData.setHas(shebao);
        // 公积金情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 3)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(1);
        jiYiHuaData.setFund(gongjijin);
        // 房产信息：1-无，2-按揭房，3-全款房；默认：1
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 3)
                .end(1);
        jiYiHuaData.setHouse(house);
        // 车产信息：1-无，2-按揭车，3-全款车；默认：1
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 3)
                .end(1);
        jiYiHuaData.setCar(car);
        // 保单情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        jiYiHuaData.setPolicy(baodanIs);
        // 芝麻分：1-无，2-600分以下，3-600~650分，4-650~700分，5-700分以上；默认：2
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(2);
        jiYiHuaData.setZhiMa(zhima);
        // 学历：1-无学历，2-初中，3-中专，4-高中，5-大专，6-本科及以上；默认：1
        Integer educationAttainment = ChooseEq.create()
                .when(apiDataExchangeParameter.getEducationAttainment(), "1", 2)
                .when(apiDataExchangeParameter.getEducationAttainment(), "2", 3)
                .when(apiDataExchangeParameter.getEducationAttainment(), "3", 4)
                .when(apiDataExchangeParameter.getEducationAttainment(), "4", 5)
                .when(apiDataExchangeParameter.getEducationAttainment(), "5", 6)
                .when(apiDataExchangeParameter.getEducationAttainment(), "6", 6)
                .end(1);
        jiYiHuaData.setEducation(educationAttainment);
        // 客户端类型：Android 或 IOS，默认：Android（可选）
        jiYiHuaData.setPlatform("Android");
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(jiYiHuaData));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("serialNo", IdUtils.getSimpleUuid());
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        // 获取响应数据
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        // 获取携带参数
        String orderId = resData.getString("applyNo");
        String productName = resData.getString("productName");
        String companyName = resData.getString("companyName");
        String logo = resData.getString("logo");
        BigDecimal price = resData.getBigDecimal("price");
        // 获取手机号掩码
        List<String> listPhoneMd5 = new ArrayList<>();
        JSONArray jsonArray = resData.getJSONArray("md5List");
        IteratorUtils.array(jsonArray, (item, index) -> {
            String phoneMd5  = jsonArray.getString(index);
            listPhoneMd5.add(phoneMd5);
        });

        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

        result.setApplyId(orderId);
        result.setProductName(productName);
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setListPhoneMd5(listPhoneMd5);
        result.setDisplayName(companyName);
        listRespPlatformPhoneMaskDataExchange.add(result);

        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        // 创建进件实体类
        ApiPlatApplyJiYiHua jiYiHuaData = new ApiPlatApplyJiYiHua();
        // 手机号（明文）
        jiYiHuaData.setPhone(apiApplyParameter.getPhone());
        // 撞库返回的订单号
        jiYiHuaData.setApplyNo(apiApplyParameter.getApplyId());
        // 用户姓名（明文）
        jiYiHuaData.setUserName(apiApplyParameter.getUserName());
        // 性别（0：女，1：男），默认：1
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", 0)
                .when(apiApplyParameter.getSex(), "0", 1)
                .end(1);
        jiYiHuaData.setSex(sex);
        // 年龄，范围：20-55 岁
        jiYiHuaData.setAge(Integer.valueOf(apiApplyParameter.getAge()));
        // 用户 IP，默认：127.0.0.1
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            jiYiHuaData.setIp(apiApplyParameter.getIp());
        } else {
            jiYiHuaData.setIp("127.0.0.1");
        }
        // 贷款金额（单位：元），默认：50000 元
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(50000);
        jiYiHuaData.setLoanMoney(money);
        // 城市编码
        jiYiHuaData.setCityCode(apiApplyParameter.getAreaCode());
        // 城市名称（带“市”）
        jiYiHuaData.setCityName(apiApplyParameter.getCity());
        // 职业信息：1-上班族，2-公务员/事业单位，3-私营业主，4-个体户，5-其他；默认：1
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 5)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 2)
                .when(apiApplyParameter.getCareer(), "5", 4)
                .end(1);
        jiYiHuaData.setJob(job);
        // 最低月收入：1-4000以下，2-4000~8000，3-8000~1.5万，4-1.5万~2万，5-2万~3万，6-3万以上；默认：2
        Integer monthlySalary = ChooseEq.create()
                .when(apiApplyParameter.getMonthlySalary(), "1", 1)
                .when(apiApplyParameter.getMonthlySalary(), "2", 2)
                .when(apiApplyParameter.getMonthlySalary(), "3", 3)
                .when(apiApplyParameter.getMonthlySalary(), "4", 5)
                .when(apiApplyParameter.getMonthlySalary(), "5", 6)
                .end(2);
        jiYiHuaData.setMonthlyIncome(monthlySalary);
        // 营业执照情况：1-未办理，2-已办理，注册满1年，3-已办理，注册满3年，4-已办理，注册满5年以上；默认：2
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiApplyParameter.getBizLicenseYear(),"1", 1)
                .when(apiApplyParameter.getBizLicenseYear(),"2", 2)
                .when(apiApplyParameter.getBizLicenseYear(),"3", 3)
                .when(apiApplyParameter.getBizLicenseYear(),"4", 4)
                .end(2);
        jiYiHuaData.setBusLicense(bizLicenseYear);
        // 社保情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 3)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        jiYiHuaData.setHas(shebao);
        // 公积金情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 3)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        jiYiHuaData.setFund(gongjijin);
        // 房产信息：1-无，2-按揭房，3-全款房；默认：1
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 3)
                .end(1);
        jiYiHuaData.setHouse(house);
        // 车产信息：1-无，2-按揭车，3-全款车；默认：1
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 3)
                .end(1);
        jiYiHuaData.setCar(car);
        // 保单情况：1-无，2-6个月以下，3-6个月以上；默认：1
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        jiYiHuaData.setPolicy(baodanIs);
        // 芝麻分：1-无，2-600分以下，3-600~650分，4-650~700分，5-700分以上；默认：2
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(2);
        jiYiHuaData.setZhiMa(zhima);
        // 学历：1-无学历，2-初中，3-中专，4-高中，5-大专，6-本科及以上；默认：1
        Integer educationAttainment = ChooseEq.create()
                .when(apiApplyParameter.getEducationAttainment(), "1", 2)
                .when(apiApplyParameter.getEducationAttainment(), "2", 3)
                .when(apiApplyParameter.getEducationAttainment(), "3", 4)
                .when(apiApplyParameter.getEducationAttainment(), "4", 5)
                .when(apiApplyParameter.getEducationAttainment(), "5", 6)
                .when(apiApplyParameter.getEducationAttainment(), "6", 6)
                .end(1);
        jiYiHuaData.setEducation(educationAttainment);
        // 客户端类型：Android 或 IOS，默认：Android（可选）
        jiYiHuaData.setPlatform("Android");
        // 用户授权协议地址
        jiYiHuaData.setProtocolUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(jiYiHuaData));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("serialNo", IdUtils.getSimpleUuid());
            newMap.put("content", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
